﻿package org.xtown.bingluo.xtieba.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.StringTokenizer;

public class StringUtils {

	public static boolean checkUrl(String url) {

		if (url == null || "".equals(url))
			return false;

		if (!url.startsWith("http://"))
			return false;

		return true;
	}

	public static boolean isNull(String value) {
		if (value == null || "".equals(value))
			return true;

		return false;
	}

	public static int asNumber(String num, int defNum) {
		if (isNull(num)) {
			return defNum;
		}

		return Integer.valueOf(num);
	}

	public static String str_replace(String from, String to, String source) {
		StringBuffer bf = new StringBuffer("");
		StringTokenizer st = new StringTokenizer(source, from, true);
		while (st.hasMoreTokens()) {
			String tmp = st.nextToken();
			if (tmp.equals(from)) {
				bf.append(to);
			} else {
				bf.append(tmp);
			}
		}
		return bf.toString();
	}

	public static String getMD5(String str) {
		// StringBuilder sb = new StringBuilder(source.length * 2);
		// for (byte b : source) {
		// sb.append(Character.forDigit((b >>> 4) & 15,
		// 16)).append(Character.forDigit(b & 15, 16));
		// }
		// // return sb.toString().substring(8, 24); // 16位的加密
		// return sb.toString().substring(8, 40); // 32位的加密

		MessageDigest messageDigest = null;

		try {
			messageDigest = MessageDigest.getInstance("MD5");

			messageDigest.reset();

			messageDigest.update(str.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			System.out.println("NoSuchAlgorithmException caught!");
			System.exit(-1);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		byte[] byteArray = messageDigest.digest();

		StringBuffer md5StrBuff = new StringBuffer();

		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				md5StrBuff.append("0").append(
						Integer.toHexString(0xFF & byteArray[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}

		return md5StrBuff.toString();
	}

	public static boolean isNumeric(String str){ 
		if(str.matches("\\d*")){
			return true; 
		}else{
			return false;
		}
	}
}
